# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# Author     ：skyTree
# version    ：python 3.11
# Description：生成token，校验token
"""
from itsdangerous import URLSafeTimedSerializer, SignatureExpired, BadSignature
from flask import current_app, request
import time
from api.utils.response import to_response
from api.models import User
from flask import g
from functools import wraps
from api.utils import constants


def generate_auth_token(user_id, expiration):
    """
    生成token
    :param user_id: 用户id
    :param expiration: 过期时间
    :return: token
    """
    serializer = URLSafeTimedSerializer(current_app.config["SECRET_KEY"])
    timestamp = time.time() + constants.TOKEN_EXPIRATION_TIME
    token = serializer.dumps([user_id, timestamp])

    return token


def verify_auth_token(token, expiration):
    """
    验证token
    :param token: token
    :param expiration: 过期时间
    :return: 用户id
    """
    serializer = URLSafeTimedSerializer(current_app.config["SECRET_KEY"])
    try:
        user_id, timestamp = serializer.loads(token, max_age=expiration)
        return user_id
    except SignatureExpired:
        return to_response(10015)
    except BadSignature as e:
        return to_response(10016)


def login_required(view_function):
    @wraps(view_function)
    def wrapper(*args, **kwargs):
        try:
            token = request.authorization.token
        except Exception as e:
            return to_response(20000, msg='token不存在，请先登录！')
        user_id = verify_auth_token(token, constants.TOKEN_EXPIRATION_TIME)
        if not user_id:
            return to_response(10016)
        try:
            user = User.query.filter(User.id == user_id).first()
            g.user = user
        except Exception as e:
            return to_response(10015)
        return view_function(*args, **kwargs)

    return wrapper
